/**
 * Definition for binary tree with next pointer.
 * function TreeLinkNode(val) {
 *     this.val = val;
 *     this.left = this.right = this.next = null;
 * }
 */

/**
 * @param {TreeLinkNode} root
 * @return {void} Do not return anything, modify tree in-place instead.
 */
var connect = function(root) {
    if(!root||!root.left)return;
    let pre = root;
    let cur, head;

    head = cur = pre.left;

    while(pre){
        if(cur === pre.left){
            cur.next = pre.right;
            cur = pre.right;
        }else if(cur === pre.right){
            if(pre.next){
                pre = pre.next;
                cur.next = pre.left;
                cur = pre.left;
            }else{
                pre = head;
                if(pre.left){
                    cur = head = pre.left;
                }else{
                    break;
                }
            }
        }

    }
};